package com.ankiang.treeprint.model;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;

public class TRGroupList extends JSONObject {

    public static TRGroupList convert(JSONObject jGroup) {
        TRGroupList res = new TRGroupList();
        res.putAll(jGroup);
        return res;
    }

    public void add(TRGroupItem item) {
        this.put(String.valueOf(item.getId()), item.toJSONObject());
    }


    public int getNextId() {
        int nextId = 0;
        Iterator<Entry<String, Object>> iter = entrySet().iterator();
        while (iter.hasNext()) {
            String key = iter.next().getKey();
            JSONObject jobj = getJSONObject(key);
            if (jobj == null) {
                continue;
            }
            int id = jobj.getInteger("id");
            if (nextId < id) {
                nextId = id;
            }
        }
        nextId += 1;
        return nextId;
    }

    public JSONArray toArray() {

        JSONArray res = new JSONArray();
        Iterator<Entry<String, Object>> iter = entrySet().iterator();
        while (iter.hasNext()) {
            String key = iter.next().getKey();
            JSONObject jobj = getJSONObject(key);
            if (jobj != null) {
                res.add(jobj);
            }
        }
        return res;
    }
}
